//
//  BaiduSpeech.swift
//  Runner
//
//  Created by 刘艳qi on 2019/12/4.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//
import Foundation
import UIKit
import Flutter


class BaiduSpeech : NSObject, BDSClientASRDelegate, FlutterStreamHandler{
    
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        return nil
    }
    
    func voiceRecognitionClientWorkStatus(_ workStatus: Int32, obj aObj: Any!) {
        if (self.eventSink == nil) {
            return
        }
        
        
        if (aObj is NSError) {
            let err = (aObj as! NSError)
            let data: [String: Any] = [
                "errCode": err.code,
                "data": "",
                "code": workStatus,
            ]
            
            self.eventSink!(data)
        } else {
            let data: [String: Any] = [
                "errCode": 0,
                "data": aObj,
                "code": workStatus,
            ]
            
            self.eventSink!(data)
        }
    }
    
    var methodChannel: FlutterMethodChannel?
    var eventChannel: FlutterEventChannel?
    var methodChannelName: String = "com.ziqiangwanqiang.baidu.speech.method"
    var eventChannelName: String = "com.ziqiangwanqiang.baidu.speech.event"
    var apiKey: String = ""
    var secretKey: String = ""
    var appId: String = ""
    var asrEventManager: BDSEventManager?
    var eventSink: FlutterEventSink?
    
    
    init(window:UIWindow) {
        super.init();
        // 创建语音识别对象
        self.asrEventManager = BDSEventManager.createEventManager(withName: BDS_ASR_NAME)
        
        let controller : FlutterViewController = window.rootViewController as! FlutterViewController
        
        self.methodChannel = FlutterMethodChannel(name: methodChannelName, binaryMessenger: controller.binaryMessenger)
        let strongSelf = self
        self.methodChannel!.setMethodCallHandler({
            (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            strongSelf.hanleMethodEvent(call: call, result: result)
        })
        self.eventChannel = FlutterEventChannel(name: eventChannelName, binaryMessenger: controller.binaryMessenger)
        self.eventChannel?.setStreamHandler(self)
    }
    
    func hanleMethodEvent(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void {
        if call.method == "test" {
            self.test(result: result)
        }
        
        if call.method == "start" {
            self.start(result: result)
        }
        
        if call.method == "end" {
            self.end(result: result)
        }
        
        if call.method == "setClientConfig" {
            self.setClientConfig(call: call, result: result)
        }
    }
    
    
    func test(result: @escaping FlutterResult) -> Void {
        result("test ok")
    }
    
    func start(result: @escaping FlutterResult) -> Void {
        //设置语音识别代理
        self.asrEventManager?.setDelegate(self)
        // 参数配置：在线身份验证
        self.asrEventManager?.setParameter([self.apiKey, self.secretKey], forKey: BDS_ASR_API_SECRET_KEYS)
        //设置 APPID
        self.asrEventManager?.setParameter(self.appId, forKey: BDS_ASR_OFFLINE_APP_CODE)
        //设置vad
        let vadPath = Bundle.main.path(forResource: "bds_easr_basic_model", ofType: "dat");
        
        self.asrEventManager?.setParameter(vadPath, forKey: BDS_ASR_MODEL_VAD_DAT_FILE);
        self.asrEventManager?.setParameter(true, forKey: BDS_ASR_ENABLE_MODEL_VAD);
        self.asrEventManager?.setParameter(false, forKey: BDS_ASR_ENABLE_LONG_SPEECH)
        self.asrEventManager?.setParameter(false, forKey: BDS_ASR_NEED_CACHE_AUDIO)
        self.asrEventManager?.setParameter(nil, forKey: BDS_ASR_AUDIO_FILE_PATH)
        self.asrEventManager?.setParameter(nil, forKey: BDS_ASR_AUDIO_INPUT_STREAM)
        self.asrEventManager?.setParameter("", forKey: BDS_ASR_OFFLINE_ENGINE_TRIGGERED_WAKEUP_WORD);
        
        self.asrEventManager?.sendCommand(BDS_ASR_CMD_START)
        
        result(nil)
    }
    
    func end(result: @escaping FlutterResult) -> Void {
        self.asrEventManager?.sendCommand(BDS_ASR_CMD_STOP)
        
        result(nil)
    }
    
    func setClientConfig(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void {
        let data = call.arguments as! Dictionary<String, String>
        self.appId = data["APP_ID"]!
        self.apiKey = data["API_KEY"]!
        self.secretKey = data["SECRET_KEY"]!
        result(nil)
    }
    
    func dicValueString(_ dic:[String : Any]) -> String?{
        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str
    }
}
